package pers.xiaoliang.concurrency.example.lock;

import pers.xiaoliang.concurrency.annotation.ThreadSafe;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @version v1.0
 * @description: Lock锁 （ReentrantReadWriteLock）
 * @author: xiaoliang.liu
 * @date: 2018/7/26 21:31
 */
@ThreadSafe
public class LockExample2 {

    private static final Map<String, Data> map = new TreeMap<>();

    /** 声明ReentrantReadWriteLock实例 */
    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    /** 从实例中获得读锁 */
    private static final Lock readLock = lock.readLock();

    /** 从实例中获得写锁 */
    private static final Lock writeLock = lock.writeLock();


    public Data get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    public Data put(String key, Data value) {
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }





    class Data {}

}
